//
//  UpHotView.m
//  WuyouTang
//
//  Created by ybRRR on 2023/7/10.
//  Copyright © 2023 cat. All rights reserved.
//

#import "UpHotView.h"
#import "UphotCoinCell.h"
#import "EditPayView.h"
@interface UpHotView ()<UICollectionViewDelegate,UICollectionViewDataSource,UIGestureRecognizerDelegate>
{
    UILabel *exposureLb;
    UILabel *payLb;
    UILabel *userNumLb;
    UICollectionView *_collectionView;
    UIView *backView;
}
@property (nonatomic, strong)NSMutableArray *dataArr;
@property (nonatomic, strong)EditPayView *editPayView;

@end


@implementation UpHotView

-(instancetype)initWithFrame:(CGRect)frame
{
    self  = [super initWithFrame:frame];
    if(self){
        _dataArr = [NSMutableArray array];
        self.backgroundColor = RGBA(1, 1, 1, 0.4);
        UITapGestureRecognizer *closeTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeTapClick)];
        closeTap.delegate = self;
        [self addGestureRecognizer:closeTap];
        [self createUI];
        [self getHotLiveRules];
         
    }
    return self;
}
-(void)getHotLiveRules{
    [ WYNetworking postWithUrl:@"Popular.getHotLiveRules" Dic:@{@"uid":[Config getOwnID],@"token":[Config getOwnToken]} Suc:^(int code, id info, NSString *msg) {
        if(code == 0){
            [_dataArr removeAllObjects];
            NSDictionary *infoDic = [info firstObject];
            NSArray *rulesArr = [infoDic valueForKey:@"rules"];
            [_dataArr addObjectsFromArray:rulesArr];
            [_dataArr addObject:@{@"coin":YZMsg(@"自定义")}];
            [_collectionView reloadData];
            
            exposureLb.text = minstr([infoDic valueForKey:@"exposure"]);
            userNumLb.text = [NSString stringWithFormat:@"%@-%@人",minstr([infoDic valueForKey:@"user_min_num"]),minstr([infoDic valueForKey:@"user_max_num"])];
            if(rulesArr.count > 0){
                payLb.text =minstr([[rulesArr firstObject] valueForKey:@"coin"]);
            }
        }
    } Fail:^(id fail) {
        
    }] ;
    
}
-(void)closeTapClick{
    if(self.closeEvent){
        self.closeEvent(@"关闭",@"");
    }
}
-(void)createUI{
    backView = [[UIView alloc]init];
    backView.backgroundColor = Normal_Color;
    backView.frame = CGRectMake(0, _window_height-_window_height *0.5, _window_width, _window_height *0.5);
    [self addSubview:backView];
    
    UILabel *titleLb = [[UILabel alloc]init];
    titleLb.frame = CGRectMake(0, 10, backView.width, 20);
    titleLb.textColor = UIColor.whiteColor;
    titleLb.font = [UIFont systemFontOfSize:16];
    titleLb.text = YZMsg(@"直播上热门");
    titleLb.textAlignment = NSTextAlignmentCenter;
    [backView addSubview:titleLb];
    
    UIButton *upinfoBtn = [UIButton buttonWithType:0];
    upinfoBtn.frame = CGRectMake(backView.width-30, 10, 20, 20);
    [upinfoBtn setImage:[UIImage imageNamed:@"uphotInfo"] forState:0];
    [upinfoBtn addTarget:self action:@selector(uphotInfoClick) forControlEvents:UIControlEventTouchUpInside];
    [backView addSubview:upinfoBtn];
    
    UILabel *subTitleLb = [[UILabel alloc]init];
    subTitleLb.frame = CGRectMake(0, titleLb.bottom+5, backView.width, 20);
    subTitleLb.textColor = UIColor.grayColor;
    subTitleLb.font = [UIFont systemFontOfSize:12];
    subTitleLb.text = YZMsg(@"预计曝光量");
    subTitleLb.textAlignment = NSTextAlignmentCenter;
    [backView addSubview:subTitleLb];
    
    exposureLb = [[UILabel alloc]init];
    exposureLb.frame = CGRectMake(backView.width/2-40, subTitleLb.bottom+5, 80, 20);
    exposureLb.textColor = UIColor.grayColor;
    exposureLb.font = [UIFont systemFontOfSize:12];
    exposureLb.text = YZMsg(@"1000+");
    exposureLb.textAlignment = NSTextAlignmentCenter;
    [exposureLb setBackgroundColor:Normal_SubColor];
    [backView addSubview:exposureLb];
    
    [PublicObj lineViewWithFrame:CGRectMake(10, exposureLb.bottom+10, _window_width-20, 1) andColor:Normal_SubColor andView:backView];
    
    CGFloat pwidth = [PublicObj widthOfString:YZMsg(@"预估带来的观众数：") andFont:[UIFont systemFontOfSize:14] andHeight:20];
    UILabel *peopleLb = [[UILabel alloc]init];
    peopleLb.frame = CGRectMake(20, exposureLb.bottom+15, pwidth, 20);
    peopleLb.text =YZMsg(@"预估带来的观众数：");
    peopleLb.textColor = UIColor.grayColor;
    peopleLb.font = [UIFont systemFontOfSize:14];
    [backView addSubview:peopleLb];
    
    userNumLb= [[UILabel alloc]init];
    userNumLb.frame = CGRectMake(peopleLb.right+5, exposureLb.bottom+15, 160, 20);
    userNumLb.text =@"0";
    userNumLb.textColor = Pink_Cor;
    userNumLb.font = [UIFont systemFontOfSize:14];
    [backView addSubview:userNumLb];
    
    UILabel *peopleTipLb = [[UILabel alloc]init];
    peopleTipLb.frame = CGRectMake(20, peopleLb.bottom+5, backView.width-20, 20);
    peopleTipLb.text =YZMsg(@"实际效果与直播效果有关");
    peopleTipLb.textColor = UIColor.grayColor;
    peopleTipLb.font = [UIFont systemFontOfSize:12];
    [backView addSubview:peopleTipLb];
   
    [PublicObj lineViewWithFrame:CGRectMake(10, peopleTipLb.bottom+10, _window_width-20, 1) andColor:Normal_SubColor andView:backView];
    
    UILabel *subCoinLb = [[UILabel alloc]init];
    subCoinLb.frame = CGRectMake(20, peopleTipLb.bottom+20, pwidth, 20);
    subCoinLb.text =YZMsg(@"投放金额");
    subCoinLb.textColor = UIColor.grayColor;
    subCoinLb.font = [UIFont systemFontOfSize:14];
    [backView addSubview:subCoinLb];

    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
    flow.scrollDirection = UICollectionViewScrollDirectionVertical;
    flow.itemSize = CGSizeMake((_window_width-90)/3, 30);
    flow.minimumLineSpacing = 10;
    flow.minimumInteritemSpacing = 10;

    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(20, subCoinLb.bottom+10, backView.width-40, 120) collectionViewLayout:flow];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerNib:[UINib nibWithNibName:@"UphotCoinCell" bundle:nil] forCellWithReuseIdentifier:@"UphotCoinCell"];
    _collectionView.backgroundColor = UIColor.clearColor;
    [backView addSubview:_collectionView];
    
    
    UIView *bottomView = [[UIView alloc]init];
    bottomView.frame = CGRectMake(0, backView.height-50-ShowDiff, backView.width, 50+ShowDiff);
    bottomView.backgroundColor = RGB_COLOR(@"#272048", 1);
    [backView addSubview:bottomView];
    
    UILabel *paytitleLb = [[UILabel alloc]init];
    paytitleLb.frame = CGRectMake(12, 20, 70, 20);
    paytitleLb.font = [UIFont systemFontOfSize:16];
    paytitleLb.text = YZMsg(@"待支付：");
    paytitleLb.textColor = UIColor.whiteColor;
    [bottomView addSubview:paytitleLb];
    
    payLb = [[UILabel alloc]init];
    payLb.frame = CGRectMake(paytitleLb.right+5, 20, 80, 20);
    payLb.font = [UIFont systemFontOfSize:16];
    payLb.text = YZMsg(@"100");
    payLb.textColor = UIColor.whiteColor;
    [bottomView addSubview:payLb];
    
    UIButton *payBtn = [UIButton buttonWithType:0];
    payBtn.frame = CGRectMake(backView.width-110, 0, 110, 50);
    [payBtn setBackgroundColor:RGB_COLOR(@"#EA377F", 1)];
    [payBtn setTitle:YZMsg(@"确定支付") forState:0];
    [payBtn setTitleColor: UIColor.whiteColor forState:0];
    payBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [payBtn addTarget:self action:@selector(payBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bottomView addSubview:payBtn];
}
-(void)payBtnClick{
    NSString *titleStr = [NSString stringWithFormat:@"您将支付%@%@，进行直播上热门投放，是否继续",payLb.text,[common name_coin]];
    UIAlertController *alertcontrol = [UIAlertController alertControllerWithTitle:nil message:titleStr preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:YZMsg(@"取消") style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [cancelAction setValue:UIColor.grayColor forKey:@"_titleTextColor"];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:YZMsg(@"确定支付") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [ WYNetworking postWithUrl:@"Popular.createHotLiveOrder" Dic:@{@"uid":[Config getOwnID],@"token":[Config getOwnToken],@"nums": payLb.text} Suc:^(int code, id info, NSString *msg) {
            if(code == 0){
                NSDictionary *infos = [info firstObject];
                NSString *orderid = [infos valueForKey:@"orderid"];
                if(self.closeEvent){
                    self.closeEvent(@"确定",orderid);
                }
            }else{
                [MBProgressHUD showError:msg];
            }
        } Fail:^(id fail) {
            
        }] ;

    }];
    [cancelAction setValue:UIColor.grayColor forKey:@"_titleTextColor"];
    [sureAction setValue:Pink_Cor forKey:@"_titleTextColor"];

    [alertcontrol addAction:cancelAction];
    [alertcontrol addAction:sureAction];
    [[[YBBaseAppDelegate sharedAppDelegate] topViewController]presentViewController:alertcontrol animated:YES completion:nil];
    
    
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _dataArr.count;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(5, 5, 5, 5);
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UphotCoinCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"UphotCoinCell" forIndexPath:indexPath];
    cell.backgroundColor = RGB_COLOR(@"#272048", 1);
    cell.layer.cornerRadius = 5;
    cell.layer.masksToBounds = YES;
    cell.dataDic  = _dataArr[indexPath.item];
    return cell;
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.item == _dataArr.count-1){
        [self showEditPayView];
    }else{
        NSDictionary *itemData = _dataArr[indexPath.item];
        payLb.text =[itemData valueForKey:@"coin"];
        [self getExposureByCoin:minstr([itemData valueForKey:@"coin"])];
    }
    
}
-(void)getExposureByCoin:(NSString *)coinStr{
    [WYNetworking postWithUrl:@"Popular.getExposureByCoin" Dic:@{@"nums":coinStr} Suc:^(int code, id info, NSString *msg) {
        if(code == 0){
            NSDictionary *infoDic = [info firstObject];
            exposureLb.text =[NSString stringWithFormat:@"%@+",minstr([infoDic valueForKey:@"exposure"])];
            userNumLb.text = [NSString stringWithFormat:@"%@-%@人",minstr([infoDic valueForKey:@"user_min_num"]),minstr([infoDic valueForKey:@"user_max_num"])];

        }
        } Fail:^(id fail) {
            
        }];
}
-(void)uphotInfoClick{
    NSString *url =[NSString stringWithFormat:@"%@/appapi/page/news?id=163",h5url];
    PubH5 *h5VC = [[PubH5 alloc]init];
    h5VC.url =url;
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:h5VC animated:YES];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    NSLog(@"s0000000000:%@",NSStringFromClass([touch.view class]));
    if ([touch.view isDescendantOfView:backView] ||[touch.view isDescendantOfView:_editPayView] ) {
        return NO;
    }
    return YES;
}
-(void)showEditPayView{
    YBWeakSelf;
    _editPayView = [[EditPayView alloc]initWithFrame:CGRectMake(0, 0, _window_width, _window_height)];
    _editPayView.closeEvent = ^(NSString *type, NSString *coinStr) {
        if([type isEqual:@"确定"]){
            [weakSelf.dataArr removeLastObject];
            [weakSelf.dataArr addObject:@{@"coin":coinStr}];
            payLb.text =coinStr;
            [self getExposureByCoin:coinStr];
            NSIndexPath *lastIndex = [NSIndexPath indexPathForItem:weakSelf.dataArr.count-1 inSection:0];
            UphotCoinCell *cell = [_collectionView cellForItemAtIndexPath:lastIndex];
            cell.coinLb.text =coinStr;
//            [_collectionView reloadData];
        }
        [weakSelf.editPayView removeFromSuperview];
        weakSelf.editPayView = nil;

    };
    [self addSubview:_editPayView];
}
@end
